<!--
 * @Author: your name
 * @Date: 2020-05-15 15:11:43
 * @LastEditTime: 2020-06-11 16:43:19
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \v1.0.0\components\kmlc-com\kmlc-form-upload-video\kml-form-upload-video.vue
 -->
<template>
  <view>
    <tui-list-cell :hover="false" :arrow="false">
      <view class="tui-line-cell">
        <view class="tui-title uni-uploader-head">
          <view v-if="label" class="uni-uploader-title">
            <text v-show="emData_.rules&&emData_.rules[0]&&emData_.rules[0].required" class="isrequire">*</text>
            <text>{{label}}</text>
            </view>
          <!-- #ifdef APP-PLUS || MP-WEIXIN -->
          <view
            @click="saveFile"
            class="tui-right"
            v-show="src && typeof src == 'string'&&src.indexOf('http')>-1"
          >
            <uni-icons type="download" color="#8f8f94" size="25" />
          </view>
          <!-- #endif -->
        </view>

        
        <template v-if="!src && !readonly_">
          <view class="uni-hello-addfile" @tap="chooseVideo">+ 选择视频</view>
        </template>
        <template v-else-if="src">
          <video :src="src" class="video"></video>
        </template>
        <template v-else>
          <view class="waring">error:readonly ,but source is null</view>
        </template>
      </view>
    </tui-list-cell>
    <tui-tips ref="toast"></tui-tips>
  </view>
</template>

<script>
import {uploadFileUrl} from "@/pages/customForm/interface"
import { http } from "@/common/framework";
var sourceType = [["camera"], ["album"], ["camera", "album"]];
export default {
  props: {
    label: {
      type: String
    },
    emData: {
      type: Object,
      default: () => {
        return {};
      }
    },
    readonly: {
      type: Boolean,
      default: false
    },
    options: {
      type: Object,
      default: () => {
        return {};
      }
    },
    rules: {
      type: Array,
      default: () => {
        return [];
      }
    },
    model: {
      type: String
    },
    keyStr: {
      type: String
    }
  },
  data() {
    return {
      title: "chooseVideo",
      sourceTypeIndex: 2,
      sourceType: ["拍摄", "相册", "拍摄或相册"],
      src: "",
      cameraList: [
        {
          value: "back",
          name: "后置摄像头",
          checked: "true"
        },
        {
          value: "front",
          name: "前置摄像头"
        }
      ],
      cameraIndex: 0,
      readonly_: false,
      emData_: [],
      uploadPath: "",
      progress: 0
    };
  },
  created() {
    this.initEmdata();
  },
  onUnload() {
    (this.src = ""),
      (this.sourceTypeIndex = 2),
      (this.sourceType = ["拍摄", "相册", "拍摄或相册"]);
  },
  watch: {
    "emData_.options.defaultValue": function(val) {
      this.src = val;
    }
  },
  methods: {
    initEmdata() {
      this.uploadPath = uploadFileUrl;
      if (this.emData && this.emData.key) {
        this.emData_ = this.emData;
        this.sourceTypeIndex = this.emData.options.sourceTypeIndex;
        this.sizeTypeIndex = this.emData.options.sizeTypeIndex;
        this.count = this.emData.options.limit;
        this.readonly_ = this.emData.options.readonly;
        this.emData.options.defaultValue
          ? (this.src = this.emData.options.defaultValue)
          : "";
        this.emData.options.action
          ? (this.uploadPath = this.emData.options.action)
          : null;
      } else {
        this.emData_["options"] = this.options;
        this.emData_["rules"] = this.rules || [];
        this.emData_["model"] = this.model || "";
        this.emData_["key"] = this.keyStr || "";
        this.sourceTypeIndex = this.options.sourceTypeIndex;
        this.readonly_ = this.options.readonly;
        this.options.defaultValue ? (this.src = this.options.defaultValue) : "";
        this.options.action ? (this.uploadPath = this.options.action) : null;
      }
    },
    
    sourceTypeChange: function(e) {
      this.sourceTypeIndex = parseInt(e.detail.value);
    },
    chooseVideo: function() {
      let _this = this;
      uni.chooseVideo({
        camera: this.cameraList[this.cameraIndex].value,
        sourceType: sourceType[this.sourceTypeIndex],
        success: res => {
          this.src = res.tempFilePath;
          _this._uploadFile({ path: this.src });
        },
        fail: err => {
          // #ifdef MP
          uni.getSetting({
            success: res => {
              let authStatus = false;
              switch (this.sourceTypeIndex) {
                case 0:
                  authStatus = res.authSetting["scope.camera"];
                  break;
                case 1:
                  authStatus = res.authSetting["scope.album"];
                  break;
                case 2:
                  authStatus =
                    res.authSetting["scope.album"] &&
                    res.authSetting["scope.camera"];
                  break;
                default:
                  break;
              }
              if (!authStatus) {
                uni.showModal({
                  title: "授权失败",
                  content:
                    "Hello uni-app需要从您的相机或相册获取视频，请在设置界面打开相关权限",
                  success: res => {
                    if (res.confirm) {
                      uni.openSetting();
                    }
                  }
                });
              }
            }
          });
          // #endif
        }
      });
    },
    //图片上存
    async _uploadFile(rsp) {
      let _this = this;
      const path = rsp.path;
      uni.showLoading({
        title: "上传中..." + _this.progress + "%"
      });
      let parpms = {
        url: this.uploadPath,
        file: path,
        fileType: "video",
        name: "file",
        data: {
          file: path,
          fileType: "video"
        },
        onSuccess: function(Res) {
          Res = typeof Res == "string" ? JSON.parse(Res) : Res;
          uni.hideLoading();
          if (Res && Res.success) {
            _this.src = Res.result.path;
            _this.$emit("onChangeVal", _this.src);
          } else {
            uni.showToast({
              icon: "none",
              title: Res.message || "保存失败~！"
            });
          }
        },
        onFail: function(res) {
          uni.hideLoading();
          uni.showToast({
            icon: "none",
            title: res.message || "保存失败~！"
          });
        },
        onProgressUpdate: function(res) {
          _this.progress = res.progress;
        }
      };
      http.upload(parpms);
    },
    saveFile() {
      if (
        this.src &&
        typeof this.src == "string" &&
        this.src.indexOf("http") > -1
      ) {
        uni.downloadFile({
          url: this.src,
          success: res => {
            uni.saveFile({
              tempFilePath: res.tempFilePath,
              success: res => {
                this.savedFilePath = res.savedFilePath;
                let options = {
                  msg: "保存成功，方便后续发送给其他人~",
                  duration: 2000,
                  type: "green"
                };
                this.$refs.toast.showTips(options);
              },
              fail: res => {
                let options = {
                  msg: "保存失败，请检查资源是否正确~",
                  duration: 2000,
                  type: "danger"
                };
                this.$refs.toast.showTips(options);
              }
            });
          }
        });
      }
    }
  },
  modal: {
    prop: "src",
    event: "onChangeVal"
  }
};
</script>

<style lang="scss">
.video {
  width: 92vw;
}

.camera-tips {
  padding: 10rpx 30rpx;
}
.uni-hello-addfile {
  width: 92vw;
  box-sizing: border-box;
  text-align: center;
  line-height: 144px;
  background: #fff;
  padding: 24px;
  font-size: 15px;
  color: #808080;
}
.waring {
  color: #d41200;
}
.tui-right {
  margin-left: auto;
  font-size: 26upx;
  line-height: 1;
  color: #999;
}
 .isrequire{ color:#d41200;}
</style>